<template>
  <div>
    <!-- 头部导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 主体区域 -->
    <el-card class="box-card">
      <!-- 搜索添加区域 -->
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="addRoleDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 用户信息区域 -->
      <el-table :data="rolesList" stripe>
        <el-table-column type="expand" width="50px">
          <template slot-scope="scope">
            <el-row :class="['b-bottom',index1 === 0?'b-top':'']" v-for="(item1,index1) in scope.row.children" :key="item1.id" class="vertical-middle">
              <el-col :span="6">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="18" v-if="item1.children.length > 0">
                <el-row :class="[index2 === 0?'':'b-top']" v-for="(item2,index2) in item1.children" :key="item2.id" class="vertical-middle">
                  <el-col :span="8">
                    <el-tag closable type="success" @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="16" v-if="item2.children.length > 0">
                    <el-row>
                      <el-col>
                        <el-tag  v-for="item3 in item2.children" :key="item3.id" closable type="warning" @close="removeRightById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column width="50px" type="index" label="#" align="center"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" align="center"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editHandler(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteHandler(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="configHandler(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色区域 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="40%" :before-close="closeDialog">
      <el-form :model="roleForm" :rules="roleRules" ref="roleFormRef" label-width="80px" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="roleSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色区域 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editRoleDialogVisible"
      width="40%" :before-close="closeEditDialog">
      <el-form :model="editRoleForm" :rules="roleRules" ref="editRoleFormRef" label-width="80px" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleSubmit(editRoleForm.roleId)">确 定</el-button>
      </span>
    </el-dialog>
    <!--分配权限区域-->
    <el-dialog
      title="分配权限"
      :visible.sync="configRightDialogVisible"
      width="50%" @close="checkedKeys = []">
      <el-tree
        :data="rightsList"
        show-checkbox
        default-expand-all
        :default-checked-keys="checkedKeys"
        node-key="id"
        ref="roleTreeRef"
        highlight-current
        :props="{children: 'children', label: 'authName'}">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="configRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="configRoleSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      rolesList: [],
      rightsList: [],
      addRoleDialogVisible: false,
      editRoleDialogVisible: false,
      configRightDialogVisible: false,
      checkedKeys: [],
      currentRoleId: undefined,
      roleForm: {
        roleName: '',
        roleDesc: ''
      },
      editRoleForm: {},
      roleRules: {
        roleName: [
          {
            required: true, message: '请输入账号', trigger: 'blur'
          }
        ],
        roleDesc: [
          {
            required: true, message: '请输入密码', trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    async getRoleList () {
      let { data: res } = await this.$http.get('roles')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.rolesList = res.data
    },
    async getRightList () {
      const { data: res } = await this.$http.get('rights/tree')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.rightsList = res.data
    },
    closeDialog (done) {
      this.$refs.roleFormRef.resetFields()
      done()
    },
    closeEditDialog (done) {
      this.$refs.editRoleFormRef.resetFields()
      done()
    },
    // 添加角色
    roleSubmit () {
      this.$refs.roleFormRef.validate(async valid => {
        if (!valid) return this.$message.error('角色信息错误')
        let { data: res } = await this.$http.post('roles', this.roleForm)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$refs.roleFormRef.resetFields()
        this.addRoleDialogVisible = false
        this.getRoleList()
      })
    },
    // 编辑角色
    editRoleSubmit (id) {
      this.$refs.editRoleFormRef.validate(async valid => {
        if (!valid) return this.$message.error('角色信息错误')
        let { data: res } = await this.$http.put(`roles/${id}`, this.editRoleForm)
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('编辑成功')
        this.$refs.editRoleFormRef.resetFields()
        this.editRoleDialogVisible = false
        this.getRoleList()
      })
    },
    // 编辑动作处理
    async editHandler (id) {
      let { data: res } = await this.$http.get(`roles/${id}`)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editRoleForm = res.data
      this.editRoleDialogVisible = true
    },
    async deleteHandler (id) {
      let { data: res } = await this.$http.delete(`roles/${id}`)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.getRoleList()
      return this.$message.success(res.meta.msg)
    },
    async configHandler (role) {
      this.checkedKeys = []
      console.log(this.rightsList, '开始')
      this.getLeafKey(role, this.checkedKeys)
      console.log(this.checkedKeys, '结束')
      if (this.$refs.roleTreeRef) {
        this.$refs.roleTreeRef.setCheckedKeys(this.checkedKeys)
      }
      this.currentRoleId = role.id
      this.configRightDialogVisible = true
    },
    async removeRightById (role, rightId) {
      const confirm = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirm !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      role.children = res.data
    },
    getLeafKey (node, arr) {
      if (!node.children) return arr.push(node.id)
      node.children.forEach(item => {
        this.getLeafKey(item, arr)
      })
    },
    async configRoleSubmit () {
      const checks = this.$refs.roleTreeRef.getCheckedKeys()
      const halfChecks = this.$refs.roleTreeRef.getHalfCheckedKeys()
      const { data: res } = await this.$http.post(`roles/${this.currentRoleId}/rights`, { rids: checks.concat(halfChecks).join() })
      if (res.meta.status !== 200) return this.$message.error('修改权限失败')
      this.$message.success('修改权限成功')
      this.configRightDialogVisible = false
      this.getRoleList()
    }
  },
  created () {
    this.getRoleList()
    this.getRightList()
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 10px;
}

.b-top {
  border-top: 1px solid #EBEEF5;
}

.b-bottom {
  border-bottom: 1px solid #EBEEF5;
}

.vertical-middle {
  display: flex;
  align-items: center;
}
</style>
